﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DTO;
using DataService;

public partial class Admin_Devices : BasePage
{
    private int customerId;

    protected void Page_Load ( object sender, EventArgs e )
    {
        if ( AdminLogin == null )
            Response.Redirect("~/admin/login.aspx");

        Initial();
    }

    public void Initial ()
    {
        if (!string.IsNullOrEmpty(Request.Params["ac"]))
        {
            int.TryParse(Request.Params["ac"], out customerId);

            if (customerId == 0)
                Response.Redirect("~/admin/default.aspx");

            using (DeviceService service = new DeviceService())
            {
                DisplayDevices(service.GetDevices(customerId));
            }
        }
    }

    protected void btnAddDevice_Click ( object sender, EventArgs e )
    {
        Response.Redirect("~/admin/device.aspx?c=" + customerId);
    }

    protected void grdDevices_RowCommand ( object sender, GridViewCommandEventArgs e )
    {
        int deviceId = 0;
        int.TryParse(e.CommandArgument.ToString(), out deviceId);

        if ( deviceId > 0 )
        {
            if ( e.CommandName == "EditDevice" )
            {
                Response.Redirect("~/admin/device.aspx?c=" + customerId + "&d=" + deviceId);
            }
            else if ( e.CommandName == "DeleteDevice" )
            {
                DeleteDevice(deviceId);
            }
        }
    }

    private void DeleteDevice ( int deviceId )
    {
        using ( DeviceService service = new DeviceService() )
        {
            service.DeleteDevice(deviceId);
            DisplayDevices(service.GetDevices(customerId));
        }
    }
    private void DisplayDevices ( IList<Device> devices )
    {
        grdDevices.DataSource = devices;
        grdDevices.DataBind();
    }
}